package ft.app.gtig.gui.meetingfile;

import com.haulmont.cuba.core.app.DataService;
import com.haulmont.cuba.core.entity.FileDescriptor;
import com.haulmont.cuba.core.global.LoadContext;
import com.haulmont.cuba.core.global.Metadata;
import com.haulmont.cuba.gui.components.*;
import com.haulmont.cuba.gui.components.actions.BaseAction;
import com.haulmont.cuba.gui.data.DataSupplier;
import com.haulmont.cuba.gui.data.Datasource;
import com.haulmont.cuba.gui.upload.FileUploadingAPI;
import com.haulmont.cuba.gui.xml.layout.ComponentsFactory;
import ft.app.gtig.entity.Article;
import ft.app.gtig.entity.MeetingFile;
import ft.app.gtig.gui.article.ArticleEdit;
import ft.app.gtig.service.QiNiuFileStorageService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

public class MeetingFileEdit extends AbstractEditor<MeetingFile> {
  private Logger log = LoggerFactory.getLogger(getClass());

  @Inject
  private FileUploadingAPI fileUploadingAPI;

  @Inject
  private QiNiuFileStorageService qiNiuFileStorageService;

  @Inject
  private DataSupplier dataSupplier;
  @Inject
  private DataService dataService;
  @Inject
  private Metadata metadata;

  @Inject
  private Datasource<MeetingFile> meetingFileDs;

  @Inject
  private ComponentsFactory componentsFactory;

  @Inject
  private FileMultiUploadField multiUploadField;

  @Inject
  private FlowBoxLayout imageFlowBox;





  @Override
  public void init(Map<String, Object> params) {



    multiUploadField.addQueueUploadCompleteListener(() -> {

      StringBuilder image = new StringBuilder(333);

      for (Map.Entry<UUID, String> entry : multiUploadField.getUploadsMap().entrySet()) {
        UUID fileId = entry.getKey();
        String fileName = entry.getValue();

        FileDescriptor srcFd = fileUploadingAPI.getFileDescriptor(fileId, fileName);

        FileDescriptor dstFd = dataSupplier.commit(srcFd);

        qiNiuFileStorageService.uploadFile(fileUploadingAPI.getFile(fileId), dstFd.getId().toString());

        image.append(dstFd.getId());
        image.append(",");
      }

      if (image.length() > 0) {
        getItem().setImage(image.toString());
        displayImage();
      }

      showNotification("Uploaded files: " + multiUploadField.getUploadsMap().values(), NotificationType.HUMANIZED);
      multiUploadField.clearUploads();
    });

    multiUploadField.addFileUploadErrorListener(event ->
      showNotification("File upload error", NotificationType.HUMANIZED));
  }

  @Override
  protected void postInit() {
    displayImage();
  }

  private void displayImage() {
    imageFlowBox.removeAll();
    if (getItem().getImage() == null) {
      return;
    }

    String[] imagesId = StringUtils.split(getItem().getImage(), ',');
    if (imagesId.length == 0) {
      return;
    }

    for (String imgId : imagesId) {
      UUID fileId = UUID.fromString(imgId);
      FileDescriptor fd = dataService.load(LoadContext.create(FileDescriptor.class).setId(fileId));
      if (fd == null || fd.isDeleted()) {
        continue;
      }

      VBoxLayout embedded = createEmbedded(fd);
      if (embedded == null) {
        continue;
      }

      imageFlowBox.add(embedded);
    }
  }

  private VBoxLayout createEmbedded(FileDescriptor imageFile) {

    VBoxLayout vBoxLayout = componentsFactory.createComponent(VBoxLayout.class);
    vBoxLayout.setWidth(null);

    Embedded embedded = componentsFactory.createComponent(Embedded.class);

    try {
      embedded.setType(Embedded.Type.IMAGE);
      embedded.setSource(imageFile.getName(), qiNiuFileStorageService.downloadFile(imageFile));

      vBoxLayout.add(embedded);

      Button button = componentsFactory.createComponent(Button.class);
      button.setAlignment(Alignment.TOP_CENTER);
      button.setCaption("Clear");
      button.setAction(new BaseAction("hello") {
        @Override
        public void actionPerform(Component component) {
          imageFlowBox.remove(vBoxLayout);
//                    vBoxLayout.setVisible(false);
          MeetingFileEdit.this.clearImage(imageFile);
        }
      });
      vBoxLayout.add(button);

      return vBoxLayout;
    } catch (IOException e) {
      log.error("createEmbedded error.", e);
      return null;
    }
  }

  private void clearImage(FileDescriptor imageFile) {
    StringBuilder images = new StringBuilder(333);
    String[] srcImages = getItem().getImage().split(",");
    for (String image : srcImages) {
      if (StringUtils.equals(image, imageFile.getId().toString())) {
        continue;
      }
      images.append(image);
      images.append(",");
    }

    getItem().setImage(images.toString());
  }
}